from PIL import Image
import os
try:
    import cv2
    from mss import mss
except:
    os.system("pip3 install opencv-python mss")
    import cv2
    from mss import mss



mss().shot(output='1.1.png')



# now let's initialize the list of reference point
ref_point = []
ref_point_2 = []

def shape_selection(event, x, y, flags, param):
    # grab references to the global variables
    global ref_point, ref_point_2

    # if the left mouse button was clicked, record the starting
    # (x, y) coordinates and indicate that cropping is being performed
    if event == cv2.EVENT_LBUTTONDOWN:
        ref_point = [(x, y)]
        ref_point_2.append(y)

    # check to see if the left mouse button was released
    elif event == cv2.EVENT_LBUTTONUP:
        # record the ending (x, y) coordinates and indicate that
        # the cropping operation is finished
        ref_point.append((x, y))
        ref_point_2.append(y)

        # draw a rectangle around the region of interest
        cv2.rectangle(image, ref_point[0], ref_point[1], (0, 255, 0), 10)
        cv2.imshow("image", image)

image = cv2.imread('1.1.png')
clone = image.copy()
cv2.namedWindow("image", cv2.WINDOW_NORMAL|cv2.WINDOW_KEEPRATIO)
cv2.setMouseCallback("image", shape_selection)

# keep looping until the 'q' key is pressed
while True:
    # display the image and wait for a keypress
    cv2.imshow("image", image)
    key = cv2.waitKey(1) & 0xFF

    # press 'r' to reset the window
    if key == ord('r'):
        ref_point_2 = []
        image = clone.copy()

    elif key == ord('c') or key == ord('q'):
        ref_point_2 = []
        break

    elif key == ord('\r'):
        break
        
# close all open windows
cv2.destroyAllWindows()

#print(ref_point_2)
print(image.size)
w = image.size[0]
i = 0
img0_2 = Image.open('1.1.png')
while 2*i < len(ref_point_2):
    img0_2.crop((0,ref_point_2[2*i],w,ref_point_2[2*i+1])).save('2.out.%s.jpg' %(i+1))
    i=i+1
    